package com.ymt.basic;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ymt.bpm.service.basic.UserService;
import com.ymt.util.Const;
import com.ymt.util.Settings;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONObject;

/**

 * @ClassName: SecurityFilter

 * @Description: 用户安全认证的过滤器

 * @author Johnny

 * @date 2015-12-24 下午2:15:21
 */
public class SecurityFilter implements Filter {
	
	/**
	 * logger.
	 */
	Logger logger = Logger.getLogger(SecurityFilter.class.getName());
	
    /**
     * destroy.
     */
    public void destroy() {
        /**
         * UserProfileThread.removeProfile();
         */
    }

    /**
     * @MethodName: doFilter
     * @Description: 检查用户是否已认证
     * @param request
     * @param response
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpRes = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        
        //登录页面地址
        String loginPath = httpRequest.getContextPath() + "/login.jsp";
        
        logger.finest("doFilter request path=" + httpRequest.getRequestURI());
        //get session
        HttpSession session = httpRequest.getSession(false);
        
        //get login user
        String remoteUser = httpRequest.getRemoteUser();
        
        logger.finest("remoteUser=" + remoteUser);
        
        //如果未认证，跳转到登录页面
        if (remoteUser==null) {
        	httpRes.sendRedirect(loginPath);
        	return;
        }
        
        try {
            
            /**
             * JAAS Authentication
             */
            if (remoteUser != null && (session==null || session.getAttribute(Const.LOGINNAME)==null)) {//用户已认证但session信息为空
            	logger.finest("remoteUser not in session.");
            	if (session==null) {
            		logger.finest("session is null.");
            		session = httpRequest.getSession();
            	}
            	//获取用户信息服务类
            	WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            	UserService us = (UserService) wac.getBean("userServiceImpl");
            	JSONObject user = us.getUserInfoDetail(remoteUser);
            	//put login name to session
            	String loginName = remoteUser.toLowerCase();
            	session.setAttribute(Const.LOGINNAME, loginName);
            	session.setAttribute(Const.DISPLAYNAME, user.get(Const.DISPLAYNAME));
            	session.setAttribute(Const.LANG, Const.LANG_ZH);
            	session.setAttribute(Const.ORGS, user.getJSONArray(Const.ORGS).toJSONString());
            	session.setAttribute(Const.ROLES, user.getJSONArray(Const.ROLES).toJSONString());
            	//JSONObject profile = us.getUserProfile(remoteUser);
            	//session.setAttribute("dhxskin", profile.get("dhxskin"));
            	//session.setAttribute("dhxtheme", profile.get("dhxtheme"));
            	session.setAttribute("dhxskin", Settings.getValue("bpmp.default.dhxskin"));
            	session.setAttribute("dhxtheme", Settings.getValue("bpmp.default.dhxtheme"));
            	//put display name to session
            	/*String displayName = user.getString("userName");
            	logger.finest("displayName==="+displayName);
            	session.setAttribute(Const.DISPLAYNAME, (displayName==null || displayName.length()==0)?loginName:displayName);*/
            	logger.finer("displayName=== in session ===" + session.getAttribute(Const.DISPLAYNAME));
            	logger.finer("orgs=== in session ===" + session.getAttribute(Const.ORGS));
            	logger.finer("roles=== in session ===" + session.getAttribute(Const.ROLES));
            	/*try {
            		//SettingUtil.setSessionLang(httpRequest, remoteUser);
            	} catch(Exception e) {
            		e.printStackTrace(System.out);
            		logger.log(Level.WARNING, "doFilter： Error while setting locale info for "+remoteUser+","+e.getMessage(), e);
            		session.setAttribute(Const.LANG, Const.LANG_ZH);
            	}*/
            }
            
        } catch (Exception ex) {
        	//如果认证发生错误，返回登录页面
            ex.printStackTrace(System.out);
            logger.log(Level.WARNING, "doFilter exception:" + ex.getMessage(), ex);
            httpRes.sendRedirect(loginPath + "?retry=true");
        }
        
        //继续运行其他过滤器
        filterChain.doFilter(request, response);

    }

    /**
     * init.
     * @param config
     * 
     */
    public void init(FilterConfig config) {
    	//do nothing
    }
    
}
